import model from '../../model/client-model'
import notify from '../../components/notification/function'
import bus from '../../util/bus'


// 处理错误
const handleError = (err) => {
    if(err.code === 401) {
        notify({
            content: '用户没有登录'
        })

        bus.$emit('auth')
    }
}

export default {
    // 可以写异步代码
    updateCountAsync (store, data) {
        setTimeout(()=>{
            store.commit('updateCount', data.num)
        }, data.time)
    },


    getTodos({commit}) {
        model.getAllTodos()
            .then(data => {
                commit("getTodos", data)
            })
            .catch(err => {
                handleError(err)
            })
    },
    login({commit}, {username, password}){
        return new Promise((resolve, reject) => {
            model.login(username, password)
                .then(data => {
                    commit('doLogin', data)
                    notify({
                        comtent: '登录成功'
                    })
                    resolve()
                })
                .catch(err => {
                    handleError(err)
                    reject(err)
                    notify({
                        comtent: '登录失败'
                    })
                })
        })

    },
    addTodo({commit}, todo){
        model.createTodo(todo)
            .then(data => {
                commit('addTodo', data)
                notify({
                    content: '成功添加一条数据'
                })
            })
            .catch(err => {
                handleError(err)
            })
    },
    updateTodo({commit}, {id, todo}){
        model.updateTodo(id, todo)
            .then(data => {
                commit('updateTodo', {id, todo: data})
                notify({
                    content: '修改数据成功'
                })
            })
            .catch(err => {
                handleError(err)
            })
    },
    deleteTodo({commit}, id){
        model.deleteTodo(id)
            .then(data => {
                commit('deleteTodo', id)
                notify({
                    content: '成功删除一条数据'
                })
            })
            .catch(err => {
                handleError(err)
            })
    },
    deleteAllCompleted({commit, state}){
        const ids = state.todos.filter(t => t.completed).map(t => t.id)
        model.deleteAllCompleted(ids)
            .then(() => {
                commit('deleteAllCompleted')
                notify({
                    content: '删除全部完成'
                })
            })
            .catch(err => {
                handleError(err)
            })
    }
}

